package xin.petstore.framework.web.img;

import com.google.code.kaptcha.BackgroundProducer;
import com.google.code.kaptcha.GimpyEngine;
import com.google.code.kaptcha.text.WordRenderer;
import com.google.code.kaptcha.util.Config;

import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;


public class MyKaptcha  {

    private static int width = 60;
    private static int height = 20;
    private static Config config = InitConfigurable.getInstance().getConfig();
    /**
     *创建图片工具
     * @String 为要写入的文字，不超过5个汉字的长度
     * */
    public static BufferedImage createImage(String text) {
        WordRenderer wordRenderer = config.getWordRendererImpl();
        GimpyEngine gimpyEngine = config.getObscurificatorImpl();
        BackgroundProducer backgroundProducer = config.getBackgroundImpl();
        boolean isBorderDrawn = config.isBorderDrawn();
        width = config.getWidth();
        height = config.getHeight();
        BufferedImage bi = wordRenderer.renderWord(text, width, height);
        bi = gimpyEngine.getDistortedImage(bi);
        bi = backgroundProducer.addBackground(bi);
        Graphics2D graphics = bi.createGraphics();
        if(isBorderDrawn) {
            drawBox(graphics);
        }

        return bi;
    }
    private static void drawBox(Graphics2D graphics) {
        Color borderColor = config.getBorderColor();
        int borderThickness = config.getBorderThickness();
        graphics.setColor(borderColor);
        if(borderThickness != 1) {
            BasicStroke line1 = new BasicStroke((float)borderThickness);
            graphics.setStroke(line1);
        }

        Line2D.Double line11 = new Line2D.Double(0.0D, 0.0D, 0.0D, (double)width);
        graphics.draw(line11);
        Line2D.Double line2 = new Line2D.Double(0.0D, 0.0D, (double)width, 0.0D);
        graphics.draw(line2);
        line2 = new Line2D.Double(0.0D, (double)(height - 1), (double)width, (double)(height - 1));
        graphics.draw(line2);
        line2 = new Line2D.Double((double)(width - 1), (double)(height - 1), (double)(width - 1), 0.0D);
        graphics.draw(line2);
    }
}
